<template>
    <el-button @click="drawer = true" v-if="crud.charAt(0) === '1'">添加轮播图</el-button>
    <el-button @click="toExcel01">excel导出(用dom元素)</el-button>
    <el-button @click="toExcel02">excel导出(用json数组)</el-button>
     <!-- <el-button @click="fromExcel">excel导入</el-button> -->
    <!-- <input type="file" @change="fromExcel" /> -->
    <el-upload ref="upload" class="upload-demo" :limit="1" :on-change="changeFn" :on-exceed="handleExceed" :auto-upload="false" :show-file-list="false">
        <template #trigger>
            <el-button type="primary">excel导入</el-button>
        </template>
    </el-upload>
    <el-button @click="batchSave">批量提交</el-button>
    <el-button @click="clearAll">清空轮播图数据</el-button>
    <el-divider />

    <el-table ref="table" id="table01" :data="bannerList" height="600px" style="width: 100%">
        <el-table-column prop="bannerid" label="编号" width="180" />
        <el-table-column label="图片" width="180">
            <template #default="scope">
                <img class="img" :src="scope.row.img" />
            </template>
        </el-table-column>
        <el-table-column label="是否启用" v-if="crud.charAt(2) === '1'">
            <template #default="scope">
                <el-switch v-model="scope.row.flag" />
            </template>
        </el-table-column>
        <el-table-column label="跳转连接">
            <template #default="scope">
                <el-link :href="scope.row.link" type="primary" target="_blank">跳转连接</el-link>
            </template>
        </el-table-column>
        <el-table-column prop="alt" label="图片提示" />
        <el-table-column label="操作" v-if="crud.charAt(2) === '1' || crud.charAt(3) === '1'">
            <template #default="scope">
                <el-button type="danger" v-if="crud.charAt(3) === '1'" >删除</el-button>
                <el-button type="danger" v-if="crud.charAt(2) === '1'">修改</el-button>
            </template>
        </el-table-column>
    </el-table>
    <el-drawer v-model="drawer" title="添加轮播图" direction="rtl" :before-close="handleClose">
        <AddBannerVue ref="addBannerRef" @ok="okHandle" @cancel="closeDrawer"></AddBannerVue>
    </el-drawer>
    <hr />
    <div id="container"></div>
</template>
  
<script lang="ts" setup>
import { useRoute } from "vue-router";
import { getBannerApi, addBannerApi,clearBannerApi } from "@/api/banner";
import { onMounted, reactive, ref } from "vue";
import { ElMessageBox } from 'element-plus'
import type { UploadInstance, UploadProps, UploadRawFile,UploadFile } from 'element-plus'
import AddBannerVue from "./AddBanner.vue";
import type { IBanner } from "@/myTypes"
import { excelExport, excelExportUseJson, excelImport } from "@/utils/excelUtils";

const $route = useRoute();//this.$route

const crud: string = $route.meta.crud as string;


const bannerList = reactive<Array<IBanner>>([]);

// 清空轮播图

const clearAll=()=>{
    clearBannerApi().then(res=>{
        if(res.data.code==="200"){
            ElMessageBox.alert("清空成功", "提示", {
                confirmButtonText: "确定",
                callback: () => {
                    getBannerList();
                }
            });
        }
    }).catch(err=>{
        console.log("清空失败",err);
    })
}

// 获取轮播图的数据
function getBannerList() {
    getBannerApi().then(res => {
        if (res.data.code === "200") {
            bannerList.length = 0;
            bannerList.push(...res.data.data);
        }
    }).catch(err => {
        console.log("获取轮播图失败，err", err);
    })
}

// 在初次渲染完毕后，获取轮播图数据
// onMounted(()=>getBannerList());
getBannerList();


// 添加相关：
// 
const drawer = ref(false);

function okHandle() {
    closeDrawer();
    getBannerList();
}

// 关闭抽屉
const closeDrawer = () => {
    drawer.value = false;
}

const addBannerRef = ref();

const handleClose = (done: () => void) => {
    ElMessageBox.confirm('亲，您真的要关闭吗？')
        .then(() => {
            console.log("点了确定");
            addBannerRef.value.clearData();
            done();
        })
        .catch(() => {
            // catch error
            console.log("点了取消");
        })
}

onMounted(() => console.log("父组件：mounted"))

const toExcel01 = () => {
    excelExport(document.getElementById("table01"), "banners");
}

const toExcel02 = () => {
    // const arr = bannerList.map(item => ({
    //     bannerid: item.bannerid,
    //     img: item.img,
    //     flag: item.flag ? "是" : "否"
    // }))
    // excelExportUseJson(arr, {
    //     bannerid: "编号",
    //     img: "图片",
    //     flag: "是否启用"
    // }, "bannerList");

    excelExportUseJson(bannerList, {
        bannerid: "编号",
        img: "图片",
        flag: "是否启用",
        link: "跳转连接",
        alt: "图片提示"
    }, "bannerList");
}

// 从excel文件中导入
const fromExcel = (e: any) => {

    if (e.target.files && e.target.files.length > 0) {
        excelImport(e.target.files[0],)
            .then((arr: any) => {
                bannerList.length = 0;
                arr.forEach((item: any) => {
                    bannerList.push({
                        bannerid: item["编号"],
                        img: item["图片"],
                        flag: item["是否启用"],
                        link: item["跳转连接"],
                        alt: item["图片提示"]
                    });
                })
            })
    }
}

function batchSave() {
    let count = 0;
    bannerList.forEach((item: any) => {
        addBannerApi(item).then(() => {
            console.log(`添加成功了${++count}条`);
        })
    })
}


const upload = ref<UploadInstance>();

const handleExceed: UploadProps['onExceed'] = (files) => {

    upload.value!.clearFiles()

    const file = files[0] as UploadRawFile

    upload.value!.handleStart(file);
}

const changeFn=(file:UploadFile)=>{
    console.log("excelImport:file",file);

    excelImport(file.raw as File)
        .then((arr: any) => {
            bannerList.length = 0;
            arr.forEach((item: any) => {
                bannerList.push({
                    bannerid: item["编号"],
                    img: item["图片"],
                    flag: item["是否启用"],
                    link: item["跳转连接"],
                    alt: item["图片提示"]
                });
            })
        })

}

</script>

<style lang="scss" scoped>
.img {
    width: 100%;
    height: 100px;
}
</style>
